package com.dzm.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dzm.except.LoginException;
import com.dzm.to.LoginUser;
import com.dzm.entity.User;
import com.dzm.mapper.UserMapper;
import com.dzm.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dzm.utils.ResponseEnum;
import com.dzm.vo.LoginVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Dzm
 * @since 2024-08-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginUser getUserById(LoginVo loginVo) {
        //获取用户信息
        String username = loginVo.getUsername();
        String password = SecureUtil.md5(loginVo.getPassword());
        User user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
                .eq(User::getPassword, password));

        //有用户信息则封装
        if(!Objects.isNull(user)) {
            LoginUser loginUser = new LoginUser();
            com.dzm.to.User u = new com.dzm.to.User();
            BeanUtils.copyProperties(user, u);
            loginUser.setUser(u);
            //根据用户名查找用户权限
            loginUser.setPermissions(userMapper.getPermisByName(user.getUsername()));
            return loginUser;
        }else {
            throw new LoginException(ResponseEnum.LOGIN_EXCEPTION);
        }

    }
}
